<template>
	<a-popover v-bind="options">
		<div :style="triggerStyle" />
		<template #content>
			<div class="house-popper-desc">
				<a-skeleton :loading="loading" active :paragraph="{rows: 15}">
					<a-descriptions :column="1" :colon="false" class="ant-descriptions-blockquote">
						<!-- title="房源信息" -->
						<template #title>
							房源信息
							<a-tag v-if="talentedHouseTypeName" color="processing">{{ talentedHouseTypeName }}</a-tag>
						</template>
						<a-descriptions-item label="门牌号">{{ house.doorplate }}</a-descriptions-item>
						<a-descriptions-item v-if="house.houseType === 2" label="房间名称">{{ house.roomName }}</a-descriptions-item>
						<a-descriptions-item v-if="[1, 2].includes(house.houseType as number)" label="房源编号">
							{{ house.houseNo }}
						</a-descriptions-item>
						<a-descriptions-item label="经营模式">
							{{ (houseBizModeList.find(o => detail.houseBase?.houseBizMode === o.value) || {label: '未知'}).label }}
						</a-descriptions-item>
						<a-descriptions-item label="房源地址">
							{{ house.houseFullAddress || roomInfo.houseAddress || '未知' }}
						</a-descriptions-item>
						<a-descriptions-item label="朝向">{{ orientationMap[house.orientation] || '未知' }}</a-descriptions-item>
						<a-descriptions-item label="面积">{{ house.houseArea }}㎡</a-descriptions-item>
						<a-descriptions-item v-if="[1, 2].includes(house.houseType as number)" label="户型">
							{{ house.room }}室{{ house.livingRoom }}厅{{ house.toliet }}卫
						</a-descriptions-item>
						<a-descriptions-item v-else label="房型">
							{{ house.roomTypeName }}
						</a-descriptions-item>
						<a-descriptions-item label="底价/出租价">
							{{ house.basePrice || '无' }}-{{ house.actualPrice }}元/月
						</a-descriptions-item>
						<a-descriptions-item label="收房价" v-if="detail.houseBase?.houseBizMode == 1">
							{{ detail.houseBase?.costPrice || '-' }}元/月
						</a-descriptions-item>
						<a-descriptions-item label="可租日期">{{ dayjs(detail.avaliableDate).format("YYYY-MM-DD") }}</a-descriptions-item>
						<a-descriptions-item label="所属部门/维护人">{{ detail.deptName }}/{{ detail.stewardName }}</a-descriptions-item>
					</a-descriptions>
					<a-descriptions
						v-if="houseBook && houseBook.id"
						title="预定信息"
						:column="1"
						:colon="false"
						class="ant-descriptions-blockquote">
						<a-descriptions-item label="预定人信息">{{ houseBook.name }}/{{ houseBook.phone }}</a-descriptions-item>
						<a-descriptions-item>
							<template #label>
								{{ CERTIFICATION_TYPE_MAP[houseBook.certificateType] || '身份证' }}
							</template>
							{{ houseBook.certificateNo || '无' }}
						</a-descriptions-item>
						<a-descriptions-item label="定金">￥{{ houseBook.price }}元</a-descriptions-item>
						<a-descriptions-item label="最晚签约时间">{{ formatDate(houseBook.signDate) }}</a-descriptions-item>
						<a-descriptions-item label="预定时间">{{ houseBook.createTime }}</a-descriptions-item>
					</a-descriptions>
					<a-descriptions
						v-if="contract && contract.id"
						title="租约信息"
						:column="1"
						:colon="false"
						class="ant-descriptions-blockquote">
						<a-descriptions-item label="合同类型">{{ contract.contractType === 1 ? '个人' : '企业' }}合同</a-descriptions-item>
						<a-descriptions-item label="合同编号">{{ contract.contractNo || '暂无' }}</a-descriptions-item>
						<a-descriptions-item v-if="contract.contractType === 2" label="承租企业">
							<!-- {{ contract?.enterPriseName || '暂无' }} / {{ contract?.enterPrisePhone || '暂无' }} -->
							{{ contract.renterName }}/{{ contract.renterPhone }}
						</a-descriptions-item>
						<a-descriptions-item :label="contract.contractType === 1 ? '承租人信息' : '企业联系人信息'">
							{{ contract.contractType === 1 ? contract.renterName : contract.emergencyName }}/{{
								contract.contractType === 1 ? contract.renterPhone : contract.emergencyPhone
							}}
						</a-descriptions-item>
						<a-descriptions-item v-if="contract.contractType === 1">
							<template #label>
								{{ CERTIFICATION_TYPE_MAP[contract.certificationType] || '身份证' }}
							</template>
							{{ contract.renterIdentityCard }}
						</a-descriptions-item>
						<a-descriptions-item label="合同周期">
							{{ formatDate(contract.beginTime) }} ~ {{ formatDate(contract.endTime) }}
						</a-descriptions-item>
						<a-descriptions-item label="承租价格">￥{{ contract.price }}元/{{contract.contractRentType === 2? '日':'月'}}</a-descriptions-item>
						<a-descriptions-item label="押金">
							￥{{ XEUtils.multiply(contract.deposit, contract.depositMonth) }}元
						</a-descriptions-item>
						<a-descriptions-item label="付款方式">
							押{{ contract.depositMonth }}付{{ contract.periodMonth === 99 ? '一次性付' : contract.periodMonth }}
						</a-descriptions-item>
					</a-descriptions>
					<a-descriptions title="房源状态" class="ant-descriptions-blockquote">
						<template #extra>
							<template v-for="(v, k) in handlers" :key="k">
								<a-checkbox
									v-model:checked="roomInfo[v.field]"
									@change="e => statusChange(e, k)"
									:disabled="v.disabled.value">
									{{ v.label }}
								</a-checkbox>
							</template>
						</template>
					</a-descriptions>
					<a-descriptions title="房源备注" :column="1" class="ant-descriptions-blockquote">
						<a-descriptions-item :contentStyle="{'text-align': 'left'}">
							{{ detail.houseRoomDetail.comment || '暂无备注' }}
						</a-descriptions-item>
					</a-descriptions>
				</a-skeleton>
			</div>
			<div class="house-popper-action">
				<a-skeleton :loading="loading" active :paragraph="{rows: 15}">
					<template v-for="(action, i) in actions" :key="i">
						<a-descriptions v-if="action.visible && action.btns.some(o => o.visible)" :column="1">
							<template #title>
								<svg-icon :icon-class="action.icon" />
								{{ action.title }}
							</template>
							<template v-for="(btn, i) in action.btns" :key="i">
								<a-descriptions-item v-if="btn.visible">
									<a @click="btn.handler(btn)">
										<a-typography-text v-if="btn.type" :type="btn.type">
											{{ btn.text }}
										</a-typography-text>
										<template v-else>
											{{ btn.text }}
										</template>
									</a>
								</a-descriptions-item>
							</template>
						</a-descriptions>
					</template>
				</a-skeleton>
			</div>
		</template>
	</a-popover>
	<template v-if="visibles.components">
		<!-- 添加备注 -->
		<house-add-note v-model:visible="visibles.addNote" :house="detail" />
		<!-- 编辑房源 -->
		<house-edit-dialog v-model:visible="visibles.houseEdit" :value="house"  @close="rereshHouse" />
		<!-- 编辑房间 -->
		<house-room-edit-dialog
			v-model:visible="visibles.roomEdit"
			:detail="detail"
			:talentedHouseStatus="talentedHouseStatus"
			:value="{...house, roomTypeId:detail.roomTypeId, avaliableDate:detail.avaliableDate}"
			@close="rereshHouse" />
		<!-- 添加预定 -->
		<add-reserve-dialog v-model:visible="visibles.reserveAdd" isPreBook :houseRecord="house" @success="rereshHouse" />
		<!-- 定金转移 更名为 预定变更 -->
		<deposit-transfer v-model:visible="visibles.reserveTransfer" :id="house.houseBookId" @success="rereshHouse" />
		<!-- 作废预定 -->
		<reserve-void-dialog v-model:visible="visibles.reserveVoid" :id="house.houseBookId" @success="rereshHouse" />
		<!-- 租客退定 -->
		<retreat-dialog v-model:visible="visibles.reserveQuit" :id="house.houseBookId" @success="rereshHouse" />
		<!-- 签约租客合同 续签 -->
		<!-- 续租租客合同 -->
		<!-- <renter-sign-dialog v-model:visible="visibles.contractSign" :contract="houseContract" @success="rereshHouse" /> -->
		<signing-dialog v-model:visible="visibles.contractSign" :signing-type="'renter'" :contract="houseContract" @success="rereshHouse" />

		<!-- 租客退租 -->
		<retreat-rent-dialog
			:contract-id="contract.id"
			:house-info="house"
			v-model:visible="visibles.contractQuit"
			@success="rereshHouse" />
		<!-- 退租 前置 -->
		<retreat-rent-pre v-model:visible="visibles.contractQuitPre" :contract-id="(contract?.id as string)" @success="rereshHouse" />

		<!-- 转租 -->
		<turn-rent-dialog :contract-id="contract.id" v-model:visible="visibles.contractSublet" @success="rereshHouse" />
		<!-- 换房 -->
		<change-house-dialog
			:contract-id="contract.id"
			v-model:visible="visibles.contractChange"
			:isConfiguration="true"
			@success="rereshHouse" />
		<!-- 查看租客合同 -->
		<contract-detail-dialog
			v-model:visible="visibles.contractDetail"
			:contract-id="contract.id"
			:enterPriseContractId="detail.enterpriseContractId"
			@close="rereshHouse" />
		<!-- 定金罚没 -->
		<deposit-forfeiture-dialog :id="house.houseBookId" v-model:visible="visibles.depositConfiscation" @success="rereshHouse" />

		<!-- 详情 -->
		<house-detail-dialog
			v-model:visible="visibles.detail"
			:value="house"
			:active="detailActive"
			:enterPriseContractId="(detail.enterpriseContractId as string)"
			@close="rereshHouse" />

		<owner-sign
			v-model:visible="visibles.showSignContract"
			:contract-id="modalConfirmData.contractId"
			:contract="modalConfirmData.seveDate"
			@success="rereshHouse" />
		<owner-detail v-model:visible="visibles.ownerDetail" :contract-id="modalConfirmData.contractId" @close="rereshHouse" />
		<!-- 退租 -->
		<owner-retreat-rent v-model:visible="visibles.ownerRetreatRent" :contract-id="modalConfirmData.contractId" @success="rereshHouse" />

		<!-- 合同管理 -->
		<ContractDialog v-model:visible="visibles.contractDialog" :value="house" />
	</template>
</template>

<script lang="ts" setup>
	import {computed, createVNode, reactive, ref, toRef, watchEffect, watch} from 'vue'
	import {message, Modal} from 'ant-design-vue'
	import {QuestionCircleOutlined} from '@ant-design/icons-vue'
	import houseApi from '@/api/house-api'
	import {defaultHouse, HouseBase, houseBizModeList, HouseDetail, orientationMap} from '@/interface/house'
	import {HouseBook, RenterContract} from '@/interface/contract'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import {useStore} from '@/store/index'
	import {microApps} from '@/micros/apps'
	import XEUtils from 'xe-utils'
	import emitter from 'yuxin-base/src/utils/bus'
	import dayjs from 'dayjs'
	import {getHouseBookRule, getOwnerContractDetail} from '@/api/contract'

	// 房源相关
	import HouseAddNote from '@/components/house/house-add-note.vue'
	import HouseEditDialog from '@/components/house/edit/house-edit-dialog.vue'
	import HouseRoomEditDialog from '@/components/house/edit/house-room-edit-dialog.vue'
	import ContractDialog from '@/components/house/detail/contract-dialog.vue'

	// 合同模块功能
	import AddReserveDialog from '@/components/contract/add-reserve-dialog/index.vue'
	import RetreatDialog from '@/components/contract/reserve/retreat.vue'
	import ContractDetailDialog from '@/components/contract/contract-detail-dialog/index.vue'
	import RetreatRentDialog from '@/components/contract/tenant/retreat-rent-dialog.vue'
	import RetreatRentPre from '@/components/contract/contract-detail-dialog/renting-out/pre.vue'
	import TurnRentDialog from '@/components/contract/tenant/turn-rent-dialog.vue'
	import ChangeHouseDialog from '@/components/contract/tenant/change-house-dialog.vue'
	import RenterSignDialog from '@/components/contract/tenant/renter-sign-dialog.vue'
	import ReserveVoidDialog from '@/components/contract/reserve/to-void.vue'
	import DepositTransfer from '@/components/contract/reserve/deposit-transfer.vue'
	import DepositForfeitureDialog from '@/components/contract/reserve/deposit-forfeiture'
	import HouseDetailDialog from '@/components/house/detail/house-detail-dialog.vue'
	import SigningDialog from '@/components/contract/signing/signing-dialog.vue'
	import OwnerSign from '@/components/contract/signing/owner-sign.vue'
	import OwnerDetail from '@/components/contract/owner-modal/detail/index.vue'
	import OwnerRetreatRent from '@/components/contract/owner-modal/owner-retreat-rent/index.vue'
	import {validateFee} from '@/utils/validateFee'
	const props = defineProps<{
		value: HouseBase
		visible: boolean
		target?: Element
	}>()

	const store = useStore()

	const hasPermissions = store.hasPermissions
	const visible = ref<boolean>(false)
	const loading = ref<boolean>(false)
	const visibles = reactive<any>({
		addNote: false,
		houseEdit: false,
		roomEdit: false,
		reserveAdd: false,
		reserveVoid: false,
		reserveQuit: false,
		reserveTransfer: false,
		contractSign: false,
		contractQuit: false,
		contractQuitPre: false,
		contractSublet: false,
		contractChange: false,
		contractDetail: false,
		detail: false,
		components: false,
		// 定金罚没按钮
		depositConfiscation: false,
		//业主合同签约续签
		showSignContract: false,
		//业主合同详情
		ownerDetail: false,
		//业主合同退租
		ownerRetreatRent: false,
		// 合同列表
		contractDialog: false
	})

	const emits = defineEmits(['update:visible'])

	const options = reactive({
		trigger: 'click',
		placement: 'rightBottom',
		destroyTooltipOnHide: true,
		overlayClassName: 'house-popper',
		visible: toRef(props, 'visible'),
		onVisibleChange(visible: boolean) {
			emits('update:visible', visible)
		},
		getPopupContainer() {
			return (
				document.querySelector('#house_card_container>.ant-card-body') ||
				document.querySelector('#house_card_container>.house-grid-wrapper')
			)
		}
	})

	const talentedHouseTypeName = ref(null)

	const triggerStyle = computed(() => {
		const style = {
			position: 'fixed',
			zIndex: -1
		}

		if (props.target) {
			const rect = props.target.getBoundingClientRect()

			Object.assign(style, {
				top: rect.top + 'px',
				left: rect.left + 'px',
				width: rect.width + 'px',
				height: rect.height + 'px'
			})
		}

		return style
	})

	// 房源信息
	const rooms = ref<HouseBase[]>([])
	const house = toRef(props, 'value', defaultHouse())
	const detail = ref<HouseDetail>({
		community: {},
		houseBase: {},
		houseBaseExtend: {},
		houseRoomDetail: {},
		houseBook: {},
		renterContract: {},
		enterpriseContractId: null
	})

	// 签约data
	const houseContract = ref<RenterContract>({})

	// 房源认定状态
	const talentedHouseStatus = ref<number>(0)

	const contract = toRef(house.value, 'renterContract', {})

	const houseBook = toRef(house.value, 'houseBook', {})

	const contractVisible = (permissions: string[], type?: number) => {
		// 未进入审批或审批通过后才可进行退转换续操作
		if (type === 2 && [26].includes(contract.value?.contractStatus as number)) {
			return
		}

		// 待付款 没有退转换续操作
		if ([21].includes(contract.value?.contractStatus as number)) {
			return false
		}

		return (
			([30].includes(house.value.houseStatus as number) || contract.value?.id) &&
			![27, 12, 41].includes(contract.value?.contractStatus as number) &&
			[-1, 0, 3].includes(contract.value?.approvalStatus as number) &&
			hasPermissions(permissions)
		)
	}

	// 房间信息
	const roomInfo = reactive<any>({
		houseBook: {},
		isDirty: false,
		isConfig: false,
		isLock: false,
		isClose: false,
		houseBaseId: '',
		houseAddress: '',
		houseAlias: '',
		contractId: ''
	})

	const validateGateWayAccess = (house: HouseBase) =>
		house.accessGateWayList?.some((e: any) => e.buildingId === house.accessBuildingId || e.buildingName === '公区')

	const houseBookRuleConfig = ref<any>()
	const getHouseBookRuleConfig = () => {
		getHouseBookRule().then(res => {
			houseBookRuleConfig.value = res.data || {}
		})
	}
	//业主合同信息
	const modalConfirmData = reactive<any>({
		contractId: null,
		seveDate: {}
	})
	// 房源操作
	const actions = reactive([
		{
			title: '房源',
			visible: true,
			icon: 'house-desc',
			btns: [
				{
					text: '编辑房源',
					visible: computed(() =>
						hasPermissions(
							{
								1: 'mk_house_distributed_bjfy',
								2: 'mk_house_distributed_bjfy',
								3: 'mk_house_centralized_bjfy'
							}[house.value.houseType as number]
						)
					),
					handler() {
						if (detail.value.houseBase?.houseBizMode == 1) {
							house.value.costPrice = detail.value.houseBase?.costPrice || null
						}
						if (house.value.houseType === 3) {
							visibles.roomEdit = true
						} else {
							visibles.houseEdit = true
						}
					}
				},
				{
					text: '编辑房间',
					// visible: [2, 3].includes(house.houseType), 产品设计取消此功能
					handler() {
						house.value.costPrice = detail.value.houseBase?.costPrice || null
						console.log('编辑房间')
					}
				},
				{
					text: '转为合租',
					visible: computed(
						() => house.value.houseType === 1 && house.value.houseStatus === 11 && hasPermissions(['mk_house_distributed_zwhz'])
					),
					handler() {
						house.value.houseType = 2
						house.value.transform = true
						visibles.houseEdit = true
					}
				},
				{
					text: '转为整租',
					visible: computed(() => {
						// 所有子间均为空置状态才可转为整租
						return (
							house.value.houseType === 2 &&
							hasPermissions(['mk_house_distributed_zwzz']) &&
							rooms.value.filter(o => !o.isMainRoom && o.status === 11).length === rooms.value.length - 1
						)
					}),
					handler() {
						house.value.houseType = 1
						house.value.transform = true
						visibles.houseEdit = true
					}
				},
				{
					visible: false,
					text: '房间配置',
					handler() {
						console.log('房间配置')
					}
				},
				{
					text: '删除房间',
					type: 'danger',
					// 空置、关闭才可删除房间
					visible: computed(
						() =>
							house.value.houseType === 2 &&
							[11, 70].includes(house.value.houseStatus as number) &&
							hasPermissions(['mk_house_distributed_scfj'])
					),
					handler() {
						Modal.confirm({
							// title: '系统提示',
							// content: '房间删除后无法恢复，确定删除？',
							// centered: true,
							// icon: createVNode(QuestionCircleOutlined),
							width: 470,
							title: '系统提示',
							content: () =>
								createVNode('div', {}, [
									createVNode('div', {
										innerHTML: '请确定相关房间的在租合约、固定资产、智能设备已清空',
										class: ''
									}),
									createVNode('div', {
										innerHTML: '房间删除后无法恢复, 确定删除',
										style: 'color:red;'
									})
								]),
							centered: true,
							icon: createVNode(QuestionCircleOutlined),
							okText: '删除',
							okType: 'danger',
							async onOk() {
								if (house.value.id) {
									await houseApi.removeHouseRoom(house.value.id)
									message.success('删除成功')
									rereshHouse()
								}
							}
						})
					}
				},
				{
					text: '删除房源',
					type: 'danger',
					// 空置、关闭才可删除房源
					visible: computed(
						() =>
							hasPermissions(
								{
									1: 'mk_house_distributed_scfy',
									2: 'mk_house_distributed_scfy',
									3: 'mk_house_centralized_scfy'
								}[house.value.houseType as number]
							) &&
							[11, 70].includes(house.value.houseStatus as number) &&
							![2, 3].includes(talentedHouseStatus.value)
					),
					handler() {
						Modal.confirm({
							// title: '系统提示',
							// content: '房源删除后无法恢复，确定删除？',
							// mask: true,
							// centered: true,
							// icon: createVNode(QuestionCircleOutlined),
							width: 470,
							title: '系统提示',
							content: () =>
								createVNode('div', {}, [
									createVNode('div', {
										innerHTML: '请确定相关房间的在租合约、固定资产、智能设备已清空',
										class: ''
									}),
									createVNode('div', {
										innerHTML: '房源删除后无法恢复,确定删除',
										style: 'color:red;'
									})
								]),
							centered: true,
							icon: createVNode(QuestionCircleOutlined),
							okText: '删除',
							okType: 'danger',
							async onOk() {
								if (house.value.housePid) {
									houseApi
										.removeHouse(house.value.housePid)
										.then(res => {
											message.success('操作成功')
											rereshHouse()
										})
										.finally(() => Modal.destroyAll())
								}
							}
						})
					}
				},
				{
					visible: false,
					text: '关闭房源',
					type: 'warning',
					handler() {
						Modal.confirm({
							title: '系统提示',
							content: '是否关闭该房源？',
							mask: true,
							centered: true,
							icon: createVNode(QuestionCircleOutlined),
							async onOk() {
								console.log('ok')
							}
						})
					}
				},
				{
					text: '添加备注',
					visible: computed(() =>
						hasPermissions(
							{
								1: 'mk_house_distributed_tjbz',
								2: 'mk_house_distributed_tjbz',
								3: 'mk_house_centralized_tjbz'
							}[house.value.houseType as number]
						)
					),
					handler() {
						visibles.addNote = true
					}
				},
				{
					text: '资产管理',
					visible: hasPermissions(['mk_enterprise']),
					handler() {
						detailActive.value = 'enterprise'
						visibles.detail = true
					}
				}
			]
		},
		{
			title: '租约',
			visible: true,
			icon: 'house-contract',
			btns: [
				{
					text: '租客预定',
					visible: computed(() => [11].includes(house.value.houseStatus as number) && hasPermissions(['mk_contract_reserve_yd'])),
					handler() {
						visibles.reserveAdd = true
					}
				},
				{
					// text: '定金转移',
					text: '预定变更',
					visible: computed(
						() => houseBook.value && houseBook.value.bookStatus === 2 && hasPermissions(['mk_contract_reserve_djzy'])
					),
					handler() {
						visibles.reserveTransfer = true
					}
				},
				{
					text: '租客退定',
					type: 'danger',
					visible: computed(
						() => houseBook.value && houseBook.value.bookStatus === 2 && hasPermissions(['mk_contract_reserve_td'])
					),
					handler() {
						visibles.reserveQuit = true
					}
				},
				{
					text: '定金罚没',
					visible: computed(
						() => houseBook.value && houseBook.value.bookStatus === 2 && hasPermissions(['mk_contract_reserve_djfm'])
					),
					handler() {
						visibles.depositConfiscation = true
					}
				},
				{
					text: '预定作废',
					type: 'danger',
					visible: computed(
						() => houseBook.value && houseBook.value.bookStatus === 1 && hasPermissions(['mk_contract_reserve_zf'])
					),
					handler() {
						visibles.reserveVoid = true
					}
				},
				{
					text: '租客签约',
					visible: computed(
						() => [11, 20].includes(house.value.houseStatus as number) && hasPermissions(['mk_contract_tenant_tjzkht'])
					),
					async handler() {
						console.log(house.value,'asdasdasdasasd');
						const res = await validateFee(house.value.id)
						if(!res) return

						if (house.value.houseBook && house.value.houseBook.bookStatus === 1) {
							return Modal.warning({
								centered: true,
								title: '系统提示',
								content: '当前房源存在预定未支付记录，请先完成支付或作废后再进行签约'
							})
						}

						houseContract.value = {
							signType: 1,
							houseId: house.value.id
						}
						visibles.contractSign = true
					}
				},
				{
					text: '查看合同',
					visible: computed(
						() =>
							([30].includes(house.value.houseStatus as number) || contract.value?.id) &&
							hasPermissions(['mk_contract_renter'])
					),
					handler() {
						visibles.contractDetail = true
					}
				},
				{
					text: '合同管理',
					visible: computed(() => hasPermissions(['mk_contract_renter'])),
					handler() {
						visibles.contractDialog = true
					}
				},
				{
					text: '租客续租',
					visible: computed(() => contractVisible(['mk_contract_tenant_xz']) && contract.value?.contractType !== 2),
					handler() {
						houseContract.value = {
							signType: 2,
							contractId: contract.value?.id
						}
						visibles.contractSign = true
					}
				},
				{
					text: '租客转租',
					visible: computed(() => contractVisible(['mk_contract_tenant_zz'], 2) && contract.value?.contractType !== 2),
					handler() {
						visibles.contractSublet = true
					}
				},
				{
					text: '租客换房',
					visible: computed(() => contractVisible(['mk_contract_tenant_hf'], 2) && contract.value?.contractType !== 2),
					handler() {
						visibles.contractChange = true
					}
				},
				{
					text: '租客退租',
					type: 'danger',
					visible: computed(() => contractVisible(['mk_contract_tenant_tz']) && showBtn()),
					handler() {
						// visibles.contractQuit = true
						visibles.contractQuitPre = true
					}
				},
				{
					text: '提前预订',
					visible: computed(() => {
						const diff = dayjs(contract.value?.endTime).diff(dayjs(), 'day')

						console.log(contract.value?.endTime, diff)

						/**
						 * 1、当前日期是合同结束日期前x天， x 小于 preBookDays
						 * 2、房间预定信息 是否提前预定 isPreBook false 展示
						 * 3、房间必须是已租 houseStatus = 30
						 * 4、权限编码
						 */
						return (
							diff <= houseBookRuleConfig.value?.preBookDays &&
							!houseBook.value?.id &&
							contractVisible(['mk_contract_reserve_tqyd'])
						)
					}),
					handler() {
						visibles.reserveAdd = true
					}
				}
			]
		},
		{
			title: '租后',
			visible: true,
			icon: 'house-work-order',
			btns: [
				{
					text: '维修申请',
					action: 'repairApplication',
					visible: hasPermissions(['mk_workorder_repair_sq']),
					handler() {
						// 打开维修申请
						microApps.loadApp({
							name: 'workorder',
							container: document.createElement('div'),
							props: {
								path: '/repair',
								searchContainer: null,
								query: {
									apply: Date.now(),
									houseId: house.value.houseId
								}
							}
						})
					}
				},
				{
					text: '保洁申请',
					action: 'cleaningApplication',
					visible: hasPermissions(['mk_workorder_cleaning_sq']),
					handler() {
						// 打开保洁申请
						microApps.loadApp({
							name: 'workorder',
							container: document.createElement('div'),
							props: {
								path: '/cleaning',
								searchContainer: null,
								query: {
									apply: Date.now(),
									houseId: house.value.houseId
								}
							}
						})
					}
				},
				{
					text: '投诉申请',
					action: 'complaintApplication',
					visible: hasPermissions(['mk_workorder_complaint_sq']),
					handler() {
						// 打开投诉申请
						microApps.loadApp({
							name: 'workorder',
							container: document.createElement('div'),
							props: {
								path: '/complaint',
								searchContainer: null,
								query: {
									apply: Date.now(),
									houseId: house.value.houseId
								}
							}
						})
					}
				}
			]
		},
		{
			title: '智能设备',
			visible: true,
			icon: 'house-device',
			btns: [
				{
					text: '智能门锁',
					visible: computed(() => house.value.deviceInfos?.some(o => o.deviceType === 5) && hasPermissions(['mk_device_lock'])),
					handler() {
						const lock = house.value.deviceInfos?.find(o => o.deviceType == 5)

						if (lock) {
							microApps.loadApp({
								name: 'device',
								container: document.createElement('div'),
								props: {
									path: '/lock',
									query: {
										refresh: Date.now(),
										lockId: lock.deviceId
									}
								}
							})
						} else {
							message.warn('暂无门锁信息，请检查是否已绑定')
						}
					}
				},
				{
					text: '智能电表',
					visible: computed(
						() => house.value.deviceInfos?.some(o => o.deviceType === 4) && hasPermissions(['mk_device_electric-meter'])
					),
					handler() {
						const meter = house.value.deviceInfos?.find(o => o.deviceType == 4)

						if (meter) {
							microApps.loadApp({
								name: 'device',
								container: document.createElement('div'),
								props: {
									path: '/electric-meter',
									query: {
										refresh: Date.now(),
										deviceId: meter.deviceId,
										roomId: house.value.id
									}
								}
							})
						} else {
							message.warn('暂无电表信息，请检查是否已绑定')
						}
					}
				},
				{
					text: '智能水表',
					visible: computed(
						() =>
							house.value.deviceInfos?.some(o => [1, 2, 3].includes(o.deviceType)) &&
							hasPermissions(['mk_device_water-meter'])
					),
					handler() {
						const meter = house.value.deviceInfos?.find(o => [1, 2, 3].includes(o.deviceType))
						const devieceConcat = house.value.deviceInfos
							?.filter(o => [1, 2, 3].includes(o.deviceType))
							.sort((a, b) => a.deviceType - b.deviceType)
							.map(e => `${e.deviceId}**${e.deviceType}`)
							.join(';')
						if (meter) {
							microApps.loadApp({
								name: 'device',
								container: document.createElement('div'),
								props: {
									path: '/water-meter',
									query: {
										refresh: Date.now(),
										deviceId: devieceConcat,
										roomId: house.value.id,
										isFromRoomPage: true
									}
								}
							})
						} else {
							message.warn('暂无水表信息，请检查是否已绑定')
						}
					}
				},
				{
					text: '智能门禁',
					visible: computed(
						() =>
							!!house.value.accessBuildingId &&
							hasPermissions(['mk_device_access-control']) &&
							validateGateWayAccess(house.value)
					),
					handler() {
						microApps.loadApp({
							name: 'device',
							container: document.createElement('div'),
							props: {
								path: '/access-control/list',
								query: {
									refresh: Date.now(),
									buildingId: house.value.accessBuildingId,
									communityId: house.value.communityId,
									houseId: house.value.houseId,
									contractId: house.value?.renterContract?.id
								}
							}
						})
					}
				},
				{
					visible: false,
					text: '添加抄表',
					handler() {
						console.log('添加抄表')
					}
				}
			]
		},
		{
			title: '业主合同',
			visible: true,
			icon: 'owner',
			btns: [
				{
					text: '业主签约',
					action: 'complaintApplication',
					visible: computed(
						() =>
							detail.value.houseBase?.houseBizMode === 1 &&
							!detail.value.houseBase?.ownerContractId &&
							hasPermissions(['mk_contract_owner_yzqy'])
					),
					handler() {
						modalConfirmData.contractId = ''
						visibles.showSignContract = true
						modalConfirmData.seveDate = {
							houseId: detail.value?.housePid,
							signType: 1
						}
					}
				},
				{
					text: '查看合同',
					action: 'complaintApplication',
					visible: computed(() => detail.value.houseBase?.houseBizMode === 1 && detail.value.houseBase?.ownerContractId),
					handler() {
						modalConfirmData.contractId = detail.value.houseBase?.ownerContractId
						visibles.ownerDetail = true
					}
				},
				{
					text: '业主续租',
					action: 'complaintApplication',
					visible: computed(() => showBtnOwner() && hasPermissions(['mk_contract_owner_yzxz'])),
					handler() {
						modalConfirmData.contractId = detail.value.houseBase?.ownerContractId
						visibles.showSignContract = true
						modalConfirmData.seveDate.contractId = detail.value.houseBase?.ownerContractId
						modalConfirmData.seveDate.houseId = detail.value?.housePid
						modalConfirmData.seveDate.signType = 2
					}
				},
				{
					text: '业主退租',
					action: 'complaintApplication',
					// visible: ,
					visible: computed(() => showBtnOwner() && hasPermissions(['mk_contract_owner_yztz'])),
					handler() {
						// 打开投诉申请
						modalConfirmData.contractId = detail.value.houseBase?.ownerContractId
						visibles.ownerRetreatRent = true
					}
				}
			]
		}
	])

	/**
	 * 获取房源详情
	 */
	const getHouseDetail = () => {
		house.value.houseId = house.value.id
		house.value.houseRoomId = house.value.id
		house.value.houseAddress = house.value.houseFullAddress
		house.value.avaliableDate = formatDate(house.value.avaliableDate)

		if (house.value.id) {
			loading.value = true
			houseApi
				.getHouseRoom(house.value.id)
				.then(({data}) => {
					detail.value = data

					house.value.stewardId = data.stewardId
					house.value.houseBookId = data.houseBookId
					house.value.houseBook = houseBook.value = data.houseBook
					house.value.renterContract = contract.value = data.renterContract || {}

					// 锁房状态
					roomInfo.isDirty = data.isDirty === 1
					roomInfo.isLock = data.status === 50
					roomInfo.isConfig = data.status === 40
					roomInfo.isClose = data.status === 70
					roomInfo.houseBaseId = data.housePid
					roomInfo.houseAddress = data.fullAddress
					roomInfo.houseAlias = data.houseAlias
				})
				.finally(() => (loading.value = false))

			if (house.value.houseType === 2) {
				// 合租获取所有房间
				houseApi.houseRooms(house.value.housePid as string).then(({data}) => {
					rooms.value = data
				})
			}
		}
	}

	// 获取房源认证信息

	const getPropertyCertificationF = () => {
		houseApi.getPropertyCertification(house.value.id as string).then(({data}) => {
			talentedHouseStatus.value = data.talentedHouseStatus
			talentedHouseTypeName.value = data.talentedHouseTypeName
		})
	}

	// watchEffect(() => {
	// 	if (props.visible) {
	// 		getHouseDetail()
	// 		getHouseBookRuleConfig()
	// 		getPropertyCertificationF()
	// 		if (!visibles.components) {
	// 			visibles.components = true
	// 		}
	// 		if (detail.value.houseBase?.ownerContractId) {
	// 			getOwnerContractDetailF()
	// 		}
	// 	}
	// })
	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				getHouseDetail()
				getHouseBookRuleConfig()
				getPropertyCertificationF()
				if (!visibles.components) {
					visibles.components = true
				}
				if (detail.value.houseBase?.ownerContractId) {
					getOwnerContractDetailF()
				}
			}
		}
	)
	const ownerApprove = ref<any>(0)
	const getOwnerContractDetailF = () => {
		getOwnerContractDetail(detail.value.houseBase?.ownerContractId).then(res => {
			ownerApprove.value = res.data.approvalStatus
		})
	}

	const handlers: any = {
		dirty: {
			label: '脏房',
			field: 'isDirty',
			tips: ['是否置为脏房?', '是否清除脏房?'],
			disabled: computed(
				() =>
					!hasPermissions(
						{
							1: 'mk_house_distributed_bgzf',
							2: 'mk_house_distributed_bgzf',
							3: 'mk_house_centralized_bgzf'
						}[house.value.houseType as number]
					)
			),
			handler(checked: boolean) {
				const params = {
					id: house.value.id,
					isDirty: checked ? 1 : 0
				}
				return houseApi.stampHouse(params)
			}
		},
		config: {
			label: '配置',
			field: 'isConfig',
			tips: ['是否设为配置中?', '是否取消配置中?'],
			disabled: computed(
				() =>
					!hasPermissions(
						{
							1: 'mk_house_distributed_pzfj',
							2: 'mk_house_distributed_pzfj',
							3: 'mk_house_centralized_pzfj'
						}[house.value.houseType as number]
					) || ![11, 40].includes(house.value.status as number)
			),
			handler(checked: boolean) {
				return houseApi.configHouse(house.value.id as string, checked ? 1 : 0)
			}
		},
		lock: {
			label: '锁房',
			field: 'isLock',
			tips: ['是否锁定该房源?', '是否取消锁定该房源?'],
			disabled: computed(
				() =>
					!hasPermissions(
						{
							1: 'mk_house_distributed_bgsf',
							2: 'mk_house_distributed_bgsf',
							3: 'mk_house_centralized_bgsf'
						}[house.value.houseType as number]
					) || [20, 30, 40, 70].includes(house.value.status as number)
			),
			handler(checked: boolean) {
				return houseApi.lockHouse(house.value.id as string, checked ? 1 : 0)
			}
		},
		close: {
			label: '关闭',
			field: 'isClose',
			tips: ['是否关闭该房源?', '是否激活该房源?'],
			disabled: computed(
				() =>
					!hasPermissions(
						{
							1: 'mk_house_distributed_gbfj',
							2: 'mk_house_distributed_gbfj',
							3: 'mk_house_centralized_gbfj'
						}[house.value.houseType as number]
					) || ![11, 70].includes(house.value.status as number)
			),
			handler(checked: boolean) {
				if (house.value.id) {
					const params = {
						houseRoomId: house.value.id,
						opType: checked ? 2 : 1
					}
					return houseApi.openOrCloseHouse(params)
				}
			}
		}
	}

	/**
	 * 修改房间状态
	 */
	const statusChange = (e: any, handler: string) => {
		if (!house.value.id) {
			return
		}

		const checked = e.target.checked
		const action = handlers[handler]

		Modal.confirm({
			title: '系统提示',
			content: checked ? action.tips[0] : action.tips[1],
			mask: true,
			centered: true,
			icon: createVNode(QuestionCircleOutlined),
			async onOk() {
				await action.handler(checked)
				message.success('操作成功')
				rereshHouse()
			},
			onCancel() {
				roomInfo[action.field] = !checked
			}
		})
	}

	/**
	 * 刷新房源列表
	 */
	const rereshHouse = () => {
		// 关闭对话框刷新房源列表，传入communityId避免整个列表刷新
		setTimeout(() => emitter.emit('refreshHouse', house.value.communityId), 1000)
	}

	/**
	 * 详情tab
	 */
	const detailActive = ref<string>()

	const showBtn = () => {
		let temp = true
		if (detail.value?.enterpriseContractId && contract.value?.contractStatus === 21) {
			temp = false
		}
		return temp
	}

	// 业主合同操作按钮
	const showBtnOwner = () => {
		let temp = false
		//  ![1].includes(detail.value.renterContract?.approvalStatus as number)
		if (
			detail.value.houseBase?.houseBizMode === 1 &&
			detail.value.houseBase?.ownerContractId &&
			![1, 2, 4].includes(ownerApprove.value)
		) {
			temp = true
		}

		return temp
	}
</script>

<style lang="less">
	.house-popper {
		// 调整Popper层级避免遮挡对话框
		z-index: 99 !important;

		.ant-popover-inner-content {
			width: 500px;
			height: 560px;
			padding: 0;
			display: flex;

			.house-popper-desc {
				flex: 1;
				padding: 12px;
				overflow: auto;

				&::-webkit-scrollbar {
					display: none;
				}

				.ant-descriptions:not(:last-child) {
					margin-bottom: 12px;
					padding-bottom: 8px;
					border-bottom: 2px solid #ecf0f9;
				}

				.ant-descriptions-item-label {
					font-size: 12px !important;
				}

				.ant-descriptions-item-content {
					text-align: right;
					display: block;
					font-size: 12px;
				}
			}

			.house-popper-action {
				width: 140px;
				padding: 12px;
				overflow: auto;
				border-left: 2px solid #ecf0f9;

				&::-webkit-scrollbar {
					display: none;
				}

				.ant-descriptions-title {
					.svg-icon {
						width: 24px;
						height: 24px;
						vertical-align: bottom;
					}
				}

				.ant-descriptions-item-content {
					text-indent: 26px;
				}
			}

			.ant-descriptions {
				.ant-descriptions-header {
					margin-bottom: 4px;

					.ant-descriptions-title {
						font-size: @font-size-base;
					}
				}

				.ant-descriptions-item {
					padding-bottom: 4px;
				}
			}
		}
	}
</style>
